package com.leyou.item.web;

import com.leyou.item.pojo.Item;
import com.leyou.item.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private ItemService itemService;


    // @ResponseBody       响应体：把Java对象序列化，放到外部响应体的Body里面去
    //ResponseEntity: 里面包含了响应头，响应体等等。。
    @PostMapping        // 新增是 Post 请求
    public ResponseEntity<Item> saveItem(Item item){
        // 校验价格,,使用 REST 风格，路径占位符来传参
        if(item.getPrice() == null){
            // 参数有误失败返回400
            //return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
            throw new RuntimeException("价格不能为空");
        }
        //return itemService.saveItem(item);新增成功返回201
        item  = itemService.saveItem(item);
        return ResponseEntity.status(HttpStatus.CREATED).body(item);
    }

}
